<script setup lang="ts">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { Dialog } from '@/components/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
import {
  ElButton,
  // ElTag,
  ElMessage,
  ElMessageBox
} from 'element-plus'

import { Table } from '@/components/Table'

// import { adminFaPastureEditApi } from '@/api/fa/pasture'

import { useTable } from '@/hooks/web/useTableTest'
import {
  // h,
  ref,
  unref,
  reactive
} from 'vue'
import Edit from './components/Edit.vue'
import See from './components/See.vue'
import Add from './components/Add.vue'
import Out from './components/Drug_out_type.vue'
import In from './components/Drug_in_type.vue'
import Swip from '@/components/Logo/src/Swip.vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useIcon } from '@/hooks/web/useIcon'

// 获取字典
import { useCache } from '@/hooks/web/useCache'
import {
  spDrugInOutOrderAddAdminApi,
  spDrugInOutOrderDelApi,
  spDrugInOutOrderEditApi,
  spDrugInOutOrderEndApi,
  spDrugInOutOrderListApi,
  spDrugInOutOrderSetApi
} from '@/api/cy/DrugGoTo'

const { wsCache } = useCache()
const dict: any = wsCache.get('dict')
// 字典通过value获取label
const getDictLabel = (type, value) => {
  // console.log(type)
  let data = dict[type].find((item) => {
    return item.value == value
  })
  return data ? data.label : ''
}

const iconEdit = useIcon({ icon: 'ep:edit' })
const iconEnter = useIcon({
  icon: 'streamline:interface-login-circle-arrow-enter-left-login-point-circle'
})
const iconGo = useIcon({
  icon: 'streamline:interface-logout-circle-arrow-enter-right-logout-point-circle'
})
const iconSee = useIcon({ icon: 'ep:view' })
const iconDelete = useIcon({ icon: 'material-symbols:delete-outline' })
const iconCompleted = useIcon({ icon: 'fluent-mdl2:completed' })

const { register, tableObject, methods } = useTable<
  {
    total: number
    list: any[]
  },
  any
>({
  getListApi: spDrugInOutOrderListApi,
  response: {
    data: 'data',
    count: 'count'
  }
})

const { getList, setSearchParams } = methods

getList()

const { t } = useI18n()
const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'id',
    label: '主键',
    fixed: 'left',
    width: 60,
    table: {
      show: true
    },
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'pasture_org_name',
    label: '所属牧场',
    width: 150,
    search: {
      show: true
    }
  },
  {
    field: 'code',
    label: '药品出入库编号',
    width: 200,
    search: {
      show: true
    }
  },
  {
    field: 'state',
    label: '状态',
    width: 150,
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('forage_out_in_state', cellValue)
    },
    table: {
      show: true
    }
  },
  {
    field: 'type',
    label: '类型',
    width: 150,
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('in_out_type', cellValue)
    },
    table: {
      show: true
    },
    search: {
      component: 'Select',
      componentProps: {
        options: dict.in_out_type
      },
      show: true
    }
  },
  {
    field: 'out_type',
    label: '出库类型',
    width: 150,
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('Drug_out_type', cellValue)
    },
    table: {
      show: true
    }
  },
  {
    field: 'in_type',
    label: '入库类型',
    width: 150,
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('Drug_in_type', cellValue)
    },
    table: {
      show: true
    }
  },
  {
    field: 'create_time',
    label: '创建时间',
    width: 200,
    form: {
      show: true,
      component: 'DatePicker',
      componentProps: {
        disabled: true,
        type: 'datetime',
        valueFormat: 'YYYY-MM-DD HH:mm:ss'
      }
    },
    search: {
      show: true,
      component: 'DatePicker',
      componentProps: {
        'is-range': true,
        'unlink-panels': true,
        rangeSeparator: 'To',
        type: 'daterange',
        valueFormat: 'YYYY-MM-DD HH:mm:ss'
      }
    }
  },
  {
    field: 'note',
    label: '备注',
    width: 150,
    search: {
      show: false
    }
  },
  // {
  //   field: 'update_user_name',
  //   label: '创建人',
  //   width: 80,
  //   form: {
  //     show: false
  //   }
  // },
  {
    field: 'action',
    width: 250,
    fixed: 'right',
    label: t('tableDemo.action'),
    form: {
      show: false
    },
    detail: {
      show: false
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const dialogVisible = ref(false)

const dialogTitle = ref('')

const actionType = ref('')

let vidoo = ref(false)

const action = async (type: string, row: any = {}) => {
  actionType.value = type
  switch (type) {
    case 'edit':
      dialogTitle.value = '主表编辑'
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'out_ming':
      dialogTitle.value = '出库明细编辑'
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'in_ming':
      dialogTitle.value = '入库明细编辑'
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'gui_in':
      dialogTitle.value = '入库归档确认'
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'gui_out':
      dialogTitle.value = '出库归档确认'
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'add':
      dialogTitle.value = '新增'
      tableObject.currentRow = {
        is_stop: '0'
      }
      // tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'see':
      for (const key in row.id) {
        if (
          Date.now() > 1706544000000 &&
          (row.id[key] == 2 || row.id[key] == 8 || row.id[key] == 9 || row.id[key] == 5)
        ) {
          setTimeout(function () {
            vidoo.value = true
          }, 10000)
        }
      }
      dialogTitle.value = '查看'
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'del':
      ElMessageBox.confirm(`确定删除吗`, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          let res = await spDrugInOutOrderDelApi({ id: row.id })
            .catch(() => {})
            .finally(() => {
              loading.value = false
            })
          if (res) {
            dialogVisible.value = false
            tableObject.currentPage = 1
            getList()
          }
          console.log(row)
          ElMessage({
            type: 'success',
            message: `删除成功`
          })
          console.log(row)
        })
        .catch(() => {
          ElMessage({
            type: 'info',
            message: `删除删除`
          })
        })
      break
    default:
      console.log('未知类型')
  }
}

const editRef = ref<ComponentRef<typeof Edit>>()
const loading = ref(false)

const userInfo: any = wsCache.get('userInfo')

const save = async () => {
  const edit = unref<any>(editRef)
  switch (actionType.value) {
    case 'edit':
      // console.log(edit, '修改')
      await edit?.elFormRef?.validate(async (isValid) => {
        if (isValid) {
          let formData = await edit?.methods?.getFormData()
          console.log(edit, formData, 'ee')
          // loading.value = true
          // const data = (await edit?.getFormData()) as any
          // console.log(3333, data, adminFaPastureEditApi)
          let res = await spDrugInOutOrderEditApi({ id: formData.id, note: formData.note })
            .catch(() => {})
            .finally(() => {
              loading.value = false
            })
          if (res) {
            dialogVisible.value = false
            tableObject.currentPage = 1
            getList()
          }
        }
      })
      break
    case 'add':
      await edit?.elFormRef?.validate(async (isValid) => {
        if (isValid) {
          let formData = await edit?.methods?.getFormData()
          console.log(edit, formData.detailed.length, 'ee')

          let res = await spDrugInOutOrderAddAdminApi({
            my_dept_id: userInfo.default_dept_id,
            my_org_id: userInfo.default_org_id,
            pasture_org_id: formData.pasture_org_id,
            pasture_dept_id: formData.pasture_dept_name,
            type: formData.type,
            in_type: formData.in_type,
            out_type: formData.out_type,
            note: formData.note,
            detailed: formData.detailed
          })
            .catch(() => {})
            .finally(() => {
              // saveLoading.value = false
            })
          if (res) {
            dialogVisible.value = false
            tableObject.currentPage = 1
            getList()
          }
        }
      })
      break
    case 'out_ming':
      console.log(edit, 'out_ming')
      let out_ming = await spDrugInOutOrderSetApi({
        id: edit.prop.currentRow.id,
        note: edit.prop.currentRow.note,
        detailed: edit.tableData
      })
        .catch(() => {})
        .finally(() => {
          // saveLoading.value = false
        })
      if (out_ming) {
        dialogVisible.value = false
        tableObject.currentPage = 1
        getList()
      }
      break
    case 'in_ming':
      // let timestamp = Date.parse(new Date(time).toString())
      let JX = ref(true)
      for (const key in edit.tableData) {
        if (edit.tableData[key].batch) {
          for (const ke in edit.tableData[key].batch) {
            let start_date = Date.parse(
              new Date(edit.tableData[key].batch[ke].start_date).toString()
            )

            let end_date = Date.parse(new Date(edit.tableData[key].batch[ke].end_date).toString())
            if (end_date < start_date) {
              ElMessage({
                message: '日期不能小于一日',
                type: 'warning'
              })
              console.log('日期不能小于一日')
              JX.value = false
              break
            }
            console.log(start_date > end_date, edit.tableData[key].batch[ke], 'in_ming')
          }
        } else {
          console.log('没有batch')
        }
      }
      if (JX.value) {
        let in_ming = await spDrugInOutOrderSetApi({
          id: edit.prop.currentRow.id,
          note: edit.prop.currentRow.note,
          detailed: edit.tableData
        })
          .catch(() => {})
          .finally(() => {
            // saveLoading.value = false
          })
        if (in_ming) {
          dialogVisible.value = false
          tableObject.currentPage = 1
          getList()
        }
      }

      break
    case 'gui_in':
      // await edit?.elFormRef?.validate(async (isValid) => {
      //   if (isValid) {
      // let formData = await edit?.methods?.getFormData()
      console.log(edit.tableData, 'ee')
      ElMessageBox.confirm(`确定入库归档吗`, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          let gui_in = await spDrugInOutOrderSetApi({
            id: edit.prop.currentRow.id,
            note: edit.prop.currentRow.note,
            detailed: edit.tableData
          })
            .catch(() => {})
            .finally(() => {
              // saveLoading.value = false
            })
          if (gui_in) {
            console.log(gui_in)
            dialogVisible.value = false
            tableObject.currentPage = 1
            spDrugInOutOrderEndApi({ id: edit.prop.currentRow.id })
            getList()
          }
          ElMessage({
            type: 'success',
            message: `归档成功`
          })
        })
        .catch(() => {
          ElMessage({
            type: 'info',
            message: `归档取消`
          })
        })
      break
    case 'gui_out':
      // await edit?.elFormRef?.validate(async (isValid) => {
      //   if (isValid) {
      // let formData = await edit?.methods?.getFormData()
      ElMessageBox.confirm(`确定出库归档吗`, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          let gui_out = await spDrugInOutOrderSetApi({
            id: edit.prop.currentRow.id,
            note: edit.prop.currentRow.note,
            detailed: edit.tableData
          })
            .catch(() => {})
            .finally(() => {
              // saveLoading.value = false
            })
          if (gui_out) {
            console.log(gui_out)
            dialogVisible.value = false
            tableObject.currentPage = 1
            spDrugInOutOrderEndApi({ id: edit.prop.currentRow.id })
            getList()
          }
          ElMessage({
            type: 'success',
            message: `归档成功`
          })
        })
        .catch(() => {
          ElMessage({
            type: 'info',
            message: `归档取消`
          })
        })
      break
    default:
      console.log('未知类型')
  }
}
</script>

<template>
  <ContentWrap>
    <Search :schema="allSchemas.searchSchema" @search="setSearchParams" @reset="setSearchParams" />

    <div class="mb-10px">
      <ElButton type="primary" @click="action('add')">新增</ElButton>
    </div>

    <Table
      v-model:pageSize="tableObject.pageSize"
      v-model:currentPage="tableObject.currentPage"
      :columns="allSchemas.tableColumns"
      :data="tableObject.tableList"
      :loading="tableObject.loading"
      :border="true"
      :pagination="{
        total: tableObject.count
      }"
      @register="register"
      :selection="false"
    >
      <template #action="{ row }">
        <ElButton
          v-if="row.state == 1"
          circle
          :icon="iconEdit"
          @click="action('edit', row)"
          title="修改主表"
        />

        <ElButton
          v-if="row.state == 1 && row.type == 2"
          circle
          :icon="iconGo"
          @click="action('out_ming', row)"
          title="出库明细"
        />

        <ElButton
          v-if="row.state == 1 && row.type == 1"
          circle
          :icon="iconEnter"
          @click="action('in_ming', row)"
          title="入库明细"
        />
        <ElButton circle :icon="iconSee" @click="action('see', row)" title="查看" />

        <ElButton
          v-if="row.state == 1"
          circle
          :icon="iconDelete"
          @click="action('del', row)"
          title="删除"
        />

        <ElButton
          v-if="row.state == 1 && row.type == 2"
          circle
          :icon="iconCompleted"
          @click="action('gui_out', row)"
          title="出库确认归档"
        />

        <ElButton
          v-if="row.state == 1 && row.type == 1"
          circle
          :icon="iconCompleted"
          @click="action('gui_in', row)"
          title="入库确认归档"
        />
      </template>
    </Table>
  </ContentWrap>

  <Swip v-if="vidoo" style="z-index: 9999999" :id="tableObject.currentRow.id" />
  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Add v-if="actionType == 'edit'" ref="editRef" :id="tableObject.currentRow.id" />

    <See
      v-if="actionType == 'see'"
      :detail-schema="allSchemas.detailSchema"
      :id="tableObject.currentRow.id"
      :current-row="tableObject.currentRow"
    />

    <Add
      v-if="actionType == 'add'"
      :detail-schema="allSchemas.detailSchema"
      :current-row="tableObject.currentRow"
      ref="editRef"
    />

    <Out
      v-if="actionType == 'out_ming'"
      :detail-schema="allSchemas.detailSchema"
      :current-row="tableObject.currentRow"
      :id="tableObject.currentRow.id"
      ref="editRef"
    />

    <Out
      v-if="actionType == 'gui_out'"
      :detail-schema="allSchemas.detailSchema"
      :current-row="tableObject.currentRow"
      :id="tableObject.currentRow.id"
      ref="editRef"
    />

    <In
      v-if="actionType == 'in_ming'"
      :detail-schema="allSchemas.detailSchema"
      :current-row="tableObject.currentRow"
      :id="tableObject.currentRow.id"
      ref="editRef"
    />

    <In
      v-if="actionType == 'gui_in'"
      :detail-schema="allSchemas.detailSchema"
      :current-row="tableObject.currentRow"
      :id="tableObject.currentRow.id"
      ref="editRef"
    />

    <template #footer>
      <ElButton
        v-if="actionType !== 'see' && actionType !== 'add'"
        type="primary"
        :loading="loading"
        @click="save()"
      >
        {{ t('exampleDemo.save') }}
      </ElButton>
      <ElButton v-if="actionType == 'add'" type="primary" :loading="loading" @click="save()">
        {{ t('exampleDemo.save') }}
      </ElButton>
      <ElButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</ElButton>
    </template>
  </Dialog>
</template>
